package com.api.main.config;

import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.sql.Connection;

@Component
@Intercepts({@Signature(
        type = StatementHandler.class, //拦截构建sql语句的StatementHandler
        method = "prepare",   //里面的prepare方法
        args = {
                Connection.class,  //方法的参数
                Integer.class
        }
)})
public class AgentSqlInterceptor implements Interceptor {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler = PluginUtils.realTarget(invocation.getTarget());
        MetaObject metaStatementHandler = SystemMetaObject.forObject(statementHandler);
        BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
        String sql = boundSql.getSql();
        logger.info("之前sql语句:{}", sql);
        sql += "<!-- corp_id=1234567 -->";
        metaStatementHandler.setValue("delegate.boundSql", sql);
        return invocation.proceed();
    }
}